<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <!-- 引入样式 -->
  <link rel="stylesheet" href="../../plugins/element-ui/index.css" />
  <link rel="stylesheet" href="../../styles/common.css" />
  <link rel="stylesheet" href="../../styles/page.css" />
  <style>


    #drug-add-app .uploadImg .el-form-item__label::before{
          content: '*';
          color: #F56C6C;
          margin-right: 4px;
      }

  </style>
</head>
<body>
   <div class="addBrand-container" id="drug-add-app">
    <div class="container">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        :inline="true"
        label-width="180px"
        class="demo-ruleForm">
        <div>
          <el-form-item
            label="药品名称:"
            prop="name">
            <el-input
              v-model="ruleForm.name"
              placeholder="请填写药品名称"
              maxlength="50"/>
          </el-form-item>

<!--          <el-form-item-->
<!--            label="药品类型:"-->
<!--            prop="type">-->
<!--            <el-input-->
<!--              v-model="ruleForm.type"-->
<!--              placeholder="请填写药品类型"-->
<!--              maxlength="50"/>-->
<!--          </el-form-item>-->

          <el-form-item
                  label="药品类型:"
                  prop="type">
            <el-select
                    v-model="ruleForm.type"
                    placeholder="请选择药品类型">
              <el-option v-for="(item,index) in typeList" :key="index" :label="item.name" :value="item.id"/>
            </el-select>
          </el-form-item>

          <el-form-item
                  label="保质期（天数）:"
                  prop="shelfLife">
            <el-input
                    v-model="ruleForm.shelfLife"
                    placeholder="请填写保质期"/>
          </el-form-item>

          <el-form-item
                  label="计量单位:"
                  prop="unit">
            <el-select
                    v-model="ruleForm.unit"
                    placeholder="请选择计量单位">
              <el-option v-for="(item,index) in unitList" :key="index" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>

          <el-form-item
            label="药品图片:"
            prop="region"
            class="uploadImg">
            <el-upload
              class="avatar-uploader"
              action="/common/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :on-change="onChange"
              ref="upload">
              <img
                v-if="imageUrl"
                :src="imageUrl"
                class="avatar">
              </img>
              <i
                v-else
                class="el-icon-plus avatar-uploader-icon">
              </i>
            </el-upload>
          </el-form-item>
        </div>

        <el-form-item
                label="排序:"
                prop="sort">
          <el-input
                  v-model="ruleForm.sort"
                  placeholder="请输入排序，数值也药品排序越靠前"/>
        </el-form-item>

        <div class="address">
          <el-form-item
            label="药品描述:"
            prop="region">
            <el-input
              v-model="ruleForm.efficacy"
              type="textarea"
              :rows="3"
              placeholder="药品描述，最长200字"
              maxlength="200"
            />
          </el-form-item>
        </div>
        <div class="subBox address">
          <el-form-item>
            <el-button @click="goBack()">
              取消
            </el-button>
            <el-button
              type="primary"
              @click="submitForm('ruleForm')"
            >
              保存
            </el-button>
            <el-button
              v-if="actionType == 'add'"
              type="primary"
              class="continue"
              @click="submitForm('ruleForm','goAnd')">
              保存并继续添加药品
            </el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
    <!-- 开发环境版本，包含了有帮助的命令行警告 -->
    <script src="../../plugins/vue/vue.js"></script>
    <!-- 引入组件库 -->
    <script src="../../plugins/element-ui/index.js"></script>
    <!-- 引入axios -->
    <script src="../../plugins/axios/axios.min.js"></script>
    <script src="../../js/request.js"></script>
    <script src="../../js/validate.js"></script>
    <script src="../../js/index.js"></script>
    <script src="../../api/drug.js"></script>
    <script src="../../api/category.js"></script>
    <script>
      new Vue({
        el: '#drug-add-app',
        data() {
          return {
            id: '',
            imageUrl: '',
            unitList: [{name: '瓶',value: 0},{name: '支',value: 1},{name: '袋',value: 2}],
            typeList:[],
            ruleForm  : {
              'name': '',
              'id': '',
              'type': '',
              'shelfLife': '',
              'image': '',
              'efficacy': '',
              'unit': '',
              'sort': ''
            },
          }
        },
        computed: {
          rules () {
            return {
              'name': [{'required': true,  'message': '请填写药品名称', 'trigger': 'blur'}],
              'type': [{'required': true,  'message': '请填写药品类型', 'trigger': 'blur'}],
               'unit': [{'required': true, 'message': '请选择药品分类', 'trigger': 'change'}],
              'shelfLife': [
                {
                  'required': true,
                  validator: (rules, value, callback) => {
                    if (!value) {
                      callback(new Error('请填写菜品保质期'))
                    } else {
                      const reg = /^[1-9]\d{0,4}|0$/
                      if (reg.test(value)) {
                        value=Number(value)
                        if(value < 100000){
                          callback()
                        }else{
                          callback(new Error('药品保质期（天数）小于100000'))
                        }
                      } else {
                        callback(new Error('药品保质期格式只能为数字,且为正整数'))
                      }
                    }
                  },
                  'trigger': 'blur'
                }
              ],
              'sort': [
                {
                  validator: (rules, value, callback) => {
                    if(value==''||value==null) callback()
                      const reg = /^[1-9]\d{0,5}|0$/
                      if (!reg.test(value)) {
                          callback(new Error('格式错误'))
                        }
                      callback()
                  },
                  'trigger': 'blur'
                }
              ],
            }
          }
        },
        created() {
          this.id = requestUrlParam('id')
          this.actionType = this.id ? 'edit' : 'add'
          this.getTypeList()
          if (this.id) {
            this.init()
          }
        },
        mounted() {
        },
        methods: {
          async init () {
            queryDrugById(this.id).then(res => {
              console.log(res)
              if (String(res.code) === '1') {
                this.ruleForm = { ...res.data }
                this.imageUrl = `/common/download?name=${res.data.image}`
              } else {
                this.$message.error(res.msg || '操作失败')
              }
            })
          },

          getTypeList() {
            queryCategoryList().then(res => {
              if (res.code === 1) {
                this.typeList = res.data
              } else {
                this.$message.error(res.msg || '操作失败')
              }
            })
          },

          submitForm(formName, st) {
            this.$refs[formName].validate((valid) => {
              if (valid) {
                let params = {...this.ruleForm}
                if(!this.imageUrl){
                  this.$message.error('请上传药品图片')
                  return 
                }
                if (this.actionType == 'add') {
                  delete params.id
                  addDrug(params).then(res => {
                    if (res.code === 1) {
                      this.$message.success('药品添加成功！')
                      if (!st) {
                        this.goBack()
                      } else {
                        this.imageUrl = ''
                        this.ruleForm = {
                          'name': '',
                          'id': '',
                          'image': '',
                          'efficacy': '',
                          'shelfLife': '',
                          'type': ''
                        }
                      }
                    } else {
                      this.$message.error(res.msg || '操作失败')
                    }
                  }).catch(err => {
                    this.$message.error('请求出错了：' + err)
                  })
                } else {
                  delete params.updateTime
                  editDrug(params).then(res => {
                    if (res.code === 1) {
                      this.$message.success('药品修改成功！')
                      this.goBack()
                    } else {
                      this.$message.error(res.msg || '操作失败')
                    }
                  }).catch(err => {
                    this.$message.error('请求出错了：' + err)
                  })
                }
              } else {
                return false
              }
            })
          },

          handleAvatarSuccess (response, file, fileList) {
            // 拼接down接口预览
            if(response.code === 0 && response.msg === '未登录'){
              window.top.location.href = '/backend/page/login/login.html'
            }else{
              this.imageUrl = `/common/download?name=${response.data}`
              this.ruleForm.image = response.data
            }
          },

          onChange (file) {
            if(file){
              const suffix = file.name.split('.')[1]
              const size = file.size / 1024 / 1024 < 2
              if(['png','jpeg','jpg'].indexOf(suffix) < 0){
                this.$message.error('上传图片只支持 png、jpeg、jpg 格式！')
                this.$refs.upload.clearFiles()
                return false
              }
              if(!size){
                this.$message.error('上传文件大小不能超过 2MB!')
                return false
              }
              return file
            }
          },
          
          goBack(){
            window.parent.menuHandle({
              id: '1',
              url: '/backend/page/drug/list.html',
              name: '药品管理'
            },false)
          }
        }
      })
    </script>
</body>
</html>